<template>
	<view>
		<j-cell-group>
			<template v-for="(item, index) in powerSavingList">
				<j-cell-card :key="item.value" v-if="item.value === 0" :title="item.title" :show="true"
					:subTitle="item.subTitle" :more="false" :is-touch="false" @jfheadertap="jftappowerSaving(item)">
					<view slot="tips" v-if="item.value === Mode">
						<uni-icons custom-prefix="iconfont" type="icon-duihao" size="24" color="#FF0025">
						</uni-icons>
					</view>
					<view v-if="isShow">
						<j-cell-card ref="timeMin" v-if="Mode === 0" title="时间(分)" subTitle="设备唤醒后将在规定时间后进入单向唤醒模式"
							:show="false" :is-touch="false" :tips="interval()" border style="background: #f5f7fb"
							@jfheadertap="jfOpenBindtap">
							<template v-for="(izem, indez) in timeList">
								<j-cell v-if="izem.title != 'custom'" :key="indez" :title="izem.title" :more="false"
									@jftap="jftaptime(izem)">
									<view slot="tips" v-if="izem.Delay === Delay">
										<uni-icons custom-prefix="iconfont" type="icon-duihao" size="24"
											color="#FF0025">
										</uni-icons>
									</view>
								</j-cell>
								<j-cell-card @jfheadertap="jftaptime(izem)" v-else :key="index" title="自定义"
									:is-touch="false" :more="false" :show="volume === Delay">
									<view class="customSlider">
										<slider min="10" activeColor="#FF0025" block-size="22" max="1800"
											:show-value="false" :value="volume" @change="customChange" />
										<view class="flex justify-between align-center">
											<view class="text">00:10</view>
											<view class="text">30:00</view>
										</view>
									</view>
									<view slot="tips" class="flex align-center" v-if="volume === Delay">
										<view class="text" style="margin-right: 10rpx;">
											{{intervalNum}}
										</view>
										<uni-icons custom-prefix="iconfont" type="icon-duihao" size="24"
											color="#FF0025">
										</uni-icons>
									</view>
								</j-cell-card>
							</template>
						</j-cell-card>
					</view>
				</j-cell-card>
				<j-cell v-else :key="item.value" :title="item.title" :subTitle="item.subTitle" :more="false"
					@jftap="jftappowerSaving(item)">
					<view slot="tips" v-if="item.value === Mode">
						<uni-icons custom-prefix="iconfont" type="icon-duihao" size="24" color="#FF0025">
						</uni-icons>
					</view>
				</j-cell>
			</template>
		</j-cell-group>
		<view class="foot-button">
			<button style="z-index: 888;" class="block radius-btn" @click="saveSettings" type="operation">保存</button>
		</view>
	</view>
</template>

<script>
	const {
		getStatus,
		deviceStorage
	} = require('@/utils/util.js');
	export default {
		data() {
			return {
				powerSavingList: [{
						title: '触发模式',
						subTitle: "检测到逗留超时或按门锁时可进入预览，电量消耗较少",
						value: 0,
						id:'TriggerMode'
					},
					{
						title: '监控模式',
						subTitle: "可随时进入远程预览，电量消耗会增加",
						value: 2,
						id:'MonitorModel'
					},
					{
						title: '图传模式',
						subTitle: "设备在唤醒后会推送一张图片，之后进入单向唤醒模式，功耗低。",
						value: 1,
						id:'ImageTransmissionMode'
					},
				],
				timeList: [{
					title: '1分钟',
					Delay: 60
				}, {
					title: '3分钟',
					Delay: 180
				}, {
					title: '5分钟',
					Delay: 300
				}, {
					title: '10分钟',
					Delay: 600
				}, {
					title: '15分钟',
					Delay: 900
				}, {
					title: '30分钟',
					Delay: 1800
				}, {
					title: 'custom',
					Delay: 120
				}],
				Mode: null,
				Delay: 0,
				device: {},
				envVersion: '',
				isShow: true,
				deviceStatus: null,
				volume: 120,
				intervalNum: '2分00秒',
				customCardShow: false,
				appletIdentify:getApp().globalData.appletIdentify,
				generalIdentify:getApp().globalData.generalIdentify,
				powerSavingMode:[],
			};
		},
		onLoad(opt) {
			let enData = decodeURIComponent(opt.device)
			this.device = JSON.parse(enData)
			this.deviceStatus = getStatus(this.device.status)
			let deviceInfo = uni.getStorageSync(this.device.deviceNo);
			if(deviceInfo.powerSavingMode){
				this.powerSavingMode = deviceInfo.powerSavingMode.propValue.values || []
			}
			this.Mode = deviceInfo.powerSavingValue || null;   //获取上次保存缓存本地的设置
			if (this.deviceStatus == 'deep' || this.deviceStatus == 'OffLine') {
				this.getTailoredConfig(); //设备深度休眠或者离线使用离线设置
			} else {
				this.getconfig(); //设备在线走普通配置
			}

			let constant = getApp().globalData.constant;
			let LOCK15 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK15;
			let LOCK16 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK16;
			let LOCK17 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK17;
			let LOCKLXPARENTID = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK7;

			this.envVersion = __wxConfig.envVersion
			
			let tempList = []
			if(this.appletIdentify==this.generalIdentify){
				this.powerSavingMode.forEach((item)=>{
					this.powerSavingList.forEach((rItem,index)=>{
						if(rItem.id == item){
							tempList.push(rItem)
						}
					})
				})
			}
			this.powerSavingList = tempList
			//以前省电模式显示逻辑  目前jlink根据jvss属性去获取 博克保持原样
			// if (this.device.parentPid == LOCKLXPARENTID && this.envVersion == 'release') {
			// 	this.isShow = false
			// 	this.powerSavingList.splice(1, 1)
			// 	this.powerSavingList[0].subTitle = '监测到逗留超时或门锁被触发唤醒后5min内可进入预览，超出5min门锁进入深度休眠，电量消耗较少'
			// } else {
			// 	this.isShow = true
			// }
			console.log('省电模式===', this.device);
		},
		methods: {
			jfOpenBindtap() {
				this.$refs.timeMin[0].touchstartMore()
			},
			// 选择模式
			jftappowerSaving(e) {
				if (e.value == 0) {
					this.Delay = 300
				}
				this.Mode = e.value
			},
			// 选择触发模式时间
			jftaptime(e) {
				this.Delay = e.Delay
				// if (e.title == 'custom' ) {
				// 	this.volume = 120
				// 	this.intervalFilter(e.Delay);
				// }
			},
			// 时间滑块
			customChange(v) {
				this.volume = v.detail.value
				this.Delay = v.detail.value
				this.intervalFilter(v.detail.value);
				this.timeList.forEach((item, index) => {
					if (item.title == 'custom') {
						item.Delay = v.detail.value
					}
				})
				console.log(v, this.Delay, this.timeList, 'customChange')
			},
			// 间隔时间处理
			intervalFilter(v, r) {
				let result = parseInt(v);
				let m = Math.floor(result / 60); // 计算分钟数
				let s = result % 60; // 计算剩余的秒数
				let minutes = m < 10 ? "0" + m : m;
				let seconds = s < 10 ? "0" + s : s;
				this.intervalNum = `${minutes}分${seconds}秒`;
			},
			// tips显示
			interval() {
				let time = null;
				this.timeList.forEach((item, index) => {
					if (item.title == 'custom') {
						if (this.volume == this.Delay) {
							// time = '自定义'
							time = this.intervalNum
						}
					} else {
						if (item.Delay == this.Delay) {
							time = item.title.replace("分钟", "分") + '00秒'
						}
					}
				})
				return time
			},
			getconfig() {
				uni.showLoading({
					mask: true
				});
				let token = this.device.token;
				let data = {
					Name: 'System.Sleep',
				};
				getApp().globalData.api.getconfig(data, token, (result) => {
					console.log(result, '普通配置');
					this.$logs({
						info: '省电模式-获取离线配置',
						response: data,
						result: data
					}, 'error')
					uni.hideLoading()
					this.Mode = result['System.Sleep'].LightSleep.Mode
					let Delay = result['System.Sleep'].LightSleep.Param[0].Delay
					if (this.Mode == 0) {
						this.handleTriggerTime(Delay)
					}
					this.Delay = Delay;
					this.interval()
				});
			},
			handleTriggerTime(e) {
				const allowedValues = [60, 180, 300, 600, 900, 1800];
				if (!allowedValues.includes(e)) {
					this.volume = e;
					this.intervalFilter(e);
				}
			},
			saveSettings() {
				if (this.device.localUiKey == 'ui_doorlock_home') {
					this.getDeviceStatus(this.device.token, (res) => {
						if (this.deviceStatus == 'deep' || this.deviceStatus == 'OffLine') {
							this.setTailoredConfig() //设备深度休眠或者离线走离线配置
						} else {
							this.getLogin(() => {
								this.setconfig() //设备在线普通设置
							})
						}
					})
				} else {
					this.setconfig() //设备在线普通设置
				}
			},
			//获取设备状态
			getDeviceStatus(token, callBack) {
				const data = {
					token: [token]
				};
				getApp().globalData.api.getDeviceStatus(data, (result) => {
					this.deviceStatus = getStatus(result[0])
					this.$logs({
						info: '省电模式-获取设备状态',
						response: data,
						result: result
					}, 'error')
					if (typeof callBack == 'function') {
						callBack(this.deviceStatus)
					}
				})
			},
			getLogin(callback) {
				uni.showLoading({
					mask: true,
				});
				let token = this.device.token;
				let data = {
					encryptType: 'DISABLE',
					LoginType: 'DVRIP-Web',
					UserName: 'admin',
					PassWord: this.device.devPassWord,
					Name: 'generalinfo'
				};
				if (this.device.adminToken) {
					data.LoginToken = this.device.adminToken
					data.encryptType = 'TOKEN'
				}
				getApp().globalData.api.deviceLogin(data, token, (result) => {
					uni.hideLoading();
					if (result.data.code === 2000) {
						// 登录成功 或 已登录
						if (result.data.data.Ret === 100 || result.data.data.Ret === 104) {
							console.log('成功')
							callback()
						} // 出错
						else {
							uni.showToast({
								icon: 'none',
								title: getApp().globalData.errCodeMsg.RetCodeMsg[result.data.data.Ret] ||
									result.data.data.RetMsg,
							});
						}
					} else {
						uni.showToast({
							icon: 'none',
							title: getApp().globalData.errCodeMsg.CodeMsg[result.data.code] || result.data
								.msg
						});
					}
				})
			},
			setconfig() {
				uni.showLoading({
					mask: true
				});
				let token = this.device.token
				let data = {
					"Name": "System.Sleep",
					"System.Sleep": {
						"LightSleep": {
							"Mode": this.Mode,
							"Param": [{
								"Value": 0,
								"Delay": this.Delay
							}]
						}
					}
				};
				getApp().globalData.api.setconfig(data, token, (result) => {
					deviceStorage(this.device.deviceNo,"powerSavingValue",this.Mode)
					uni.hideLoading();
					uni.showToast({
						title: '修改成功'
					})
					setTimeout(()=>{
						uni.navigateBack({})
					},1000)
					console.log(result);
				});
			},
			getTailoredConfig(ev, type) {
				uni.showLoading({
					title: '加载中...',
					mask: true
				})
				let token = this.device.token
				let data = {
					"sn": this.device.deviceNo,
					"configs": ['System.Sleep']
				};
				getApp().globalData.api.getTailoredConfig(data, token, (result) => {
					uni.hideLoading();
					console.log(result, '离线设置获取');
					this.$logs({
						info: '省电模式-获取离线配置',
						response: data,
						result: data
					}, 'error')
					if (Object.keys(result).length === 0 && result.constructor === Object) {
						uni.showModal({
							content: '当前设备可能处于离线或深度休眠中，请手动唤醒设备后重试',
							showCancel: false,
							confirmColor: '#FF0025',
							confirmText: '确定',
							success: (res) => {
								uni.navigateBack({})
							}
						})
					} else {
						this.Mode = result['System.Sleep'].LightSleep.Mode
						let Delay = result['System.Sleep'].LightSleep.Param[0].Delay
						if (this.Mode == 0) {
							this.handleTriggerTime(Delay)
						}
						this.Delay = Delay;
						this.interval()
					}
				});
			},
			// 离线配置
			setTailoredConfig(type, status) {
				uni.showLoading({
					mask: true
				});
				let token = this.device.token
				let data = {
					"sn": this.device.deviceNo,
					"data": {
						"System.Sleep": {
							"LightSleep": {
								"Mode": this.Mode,
								"Param": [{
									"Value": 0,
									"Delay": this.Delay
								}]
							}
						}
					}
				};
				getApp().globalData.api.setTailoredConfig(data, token, (result) => {
					uni.hideLoading();
					deviceStorage(this.device.deviceNo,"powerSavingValue",this.Mode)
					console.log(result, '离线设置');
					uni.showModal({
						content: '保存成功，设备将在下一次唤醒联网后同步生效',
						showCancel: false,
						confirmColor: '#FF0025',
						confirmText: '确定',
						success: (res) => {
							uni.navigateBack({})
						}
					})
				});
			},
		}
	};
</script>
<style lang="scss">
	/deep/.cell-sub-title {
		max-width: 76vw !important;
		white-space: pre-wrap !important;
	}

	.customSlider {
		padding: 0 30rpx;
	}

	.text {
		font-size: 22rpx;
	}
    /deep/ .cell-group {
        max-height: 88vh;
        overflow-y: scroll;
    }
</style>